# 1创建浏览器对象
# 2注销对象
# 3获取弹出窗口信息
import json

import csv
# 创建工具类
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from appium import webdriver as webdriverApp # Appium的Python客户端库
from appium.options.android import UiAutomator2Options  # Android UiAutomator2驱动选项
from selenium.webdriver.common.by import By


class UtilsDriver:
    _driver=None
    _app_driver=None

    @classmethod
    def get_driver(cls):
        if cls._driver is None:
            cls._driver=webdriver.Chrome()
            cls._driver.maximize_window()
            cls._driver.implicitly_wait(10)
            # cls._driver.get("http://hmshop-test.itheima.net/")
        return cls._driver

    @classmethod
    def quite_driver(cls):
        if cls._driver is not None:
            cls.get_driver().quit()
            cls._driver=None

    @classmethod
    def get_app_diver(cls):
        if cls._app_driver is None:
            # 导入必要的模块
            from appium.options.android import UiAutomator2Options
            from appium import webdriver as webdriverApp

            # 配置Appium连接选项
            options = UiAutomator2Options()  # 创建UiAutomator2选项对象

            # 设置基本设备能力(Desired Capabilities)
            options.platform_name = "Android"  # 指定平台为Android
            options.automation_name = "UiAutomator2"  # 使用UiAutomator2自动化引擎
            options.device_name = "emulator-5554"  # 指定设备名称(adb devices获取)
            options.app_package = "com.jingdong.app.mall"  # 要测试的App包名，修改为京东的包名
            options.app_activity = ".main.MainActivity"  # 要启动的Activity名称，修改为京东的Activity
            options.new_command_timeout = 300  # 新命令超时时间(秒)
            options.udid = "emulator-5554"  # 明确指定设备UDID
            # 初始化Appium WebDriver
            # 参数1: Appium服务器地址(默认本地4723端口)
            # 参数2: 配置选项
            cls._app_driver = webdriverApp.Remote(
                command_executor='http://127.0.0.1:4723',  # Appium服务器地址
                options=options  # 传入配置选项
            )
            return cls._app_driver
    @classmethod
    def quite_app_driver(cls):
        if cls._app_driver is not None:
            cls.get_app_diver().quit()
            cls._app_driver = None

def get_mag():
    time.sleep(1)
    return UtilsDriver.get_driver().find_element(By.CSS_SELECTOR,'.layui-layer-content').text

def get_my_data_txt():
    file=open('data/my_data.txt')
    # text=file.read()
    datas=[]
    text=file.readlines()
    for line in text:
        l=line.strip().split(',')
        print(l[0],l[1],l[2])
        datas.append((l[0],l[1]))
    file.close()
    return datas

def get_data_json(filename):
    with open(filename,encoding='utf-8') as f:
        case_data=json.load(f)
        print(case_data)
    list_case_date=[]
    for case in case_data.values():
        list_case_date.append(tuple(case.values()))
    # print(list_case_date)
    return list_case_date

import xlrd
def get_data_xlsx_xlrd(filename):
    xls=xlrd.open_workbook(filename)
    sheet=xls.sheet_by_index(0)
    print(1,sheet,sheet.nrows)
    list_case_date = []
    for row_idx in range(sheet.nrows):
        processed_row = []
        for col_idx in range(1, sheet.ncols):  # 从第2列开始
            cell_type = sheet.cell_type(row_idx, col_idx)
            cell_value = sheet.cell_value(row_idx, col_idx)
            print(col_idx,cell_type,cell_value)
            # 如果是数字类型且需要保留原始精度，可用格式字符串
            if cell_type in (xlrd.XL_CELL_NUMBER, xlrd.XL_CELL_DATE):
                processed_row.append(f"{cell_value:.0f}" if cell_value.is_integer() else str(cell_value))
            else:
                processed_row.append(str(cell_value))
        list_case_date.append(tuple(processed_row))
    print(list_case_date[1:])
    return list_case_date[1:]

import pandas as pd
def get_data_xlsx_pandas(filename,sheetname):
    # 读取整个Excel文件
    # 读取指定列（A, C列）    跳过前1行，读取第2行开始的数据
    df = pd.read_excel(filename, sheet_name=sheetname,skiprows=0,dtype={'username': str,'password': str,'code': str})
    # 显示前5行数据
    df = df.fillna('')
    selected_columns = ['username', 'password','code','except']
    column_list = df[selected_columns].values.tolist()
    print(column_list)
    return column_list

import openpyxl
def get_data_xlsx_openpyxl(filename,sheetname):
    excel = openpyxl.load_workbook(filename)
    sheet1 = excel[sheetname]
    list_datas = []
    for row in range(2, sheet1.max_row + 1):
        row_data = (
            str(sheet1.cell(row=row, column=2).value) if sheet1.cell(row=row, column=2).value else "",
            str(sheet1.cell(row=row, column=3).value) if sheet1.cell(row=row, column=3).value else "",
            str(sheet1.cell(row=row, column=4).value) if sheet1.cell(row=row, column=4).value else "",
            str(sheet1.cell(row=row, column=5).value) if sheet1.cell(row=row, column=5).value else "",
        )
        list_datas.append(row_data)
    print(list_datas)
    return list_datas


def get_data_csv(filename):
    reader=csv.reader(open(filename,'r',encoding='gb2312'))
    list_case_date = []
    for row in list(reader)[1:]:
        list_case_date.append(tuple(row[1:]))
    return list_case_date

import chardet
def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        result = chardet.detect(f.read(10000))  # 读取前10000字节检测
    return result['encoding']

if __name__ == '__main__':
    print(get_my_data_txt())
    # get_data_json('data/login_case_data.json')
    # get_data_xlsx_xlrd('data/login_case_data.xls')
    # get_data_xlsx_pandas('data/login_case_data.xlsx','test')
    # get_data_xlsx_openpyxl('data/login_case_data.xlsx','test')
    # print(get_data_csv('data/login_case_data.csv'))
    # encoding = detect_encoding('data/login_case_data.csv')
    # print(encoding)





